import {Component, OnInit} from '@angular/core';
import {FileInputPluginService} from "../share/file-input-plugin.service";
import {flyIn} from "../animations/flyIn";
import {HttpService} from "../share/http.service";
import {url} from '../share/url';


@Component({
  moduleId: module.id,
  selector: 'my-system_dictionary',
  templateUrl: 'system_dictionary.component.html',
  animations: [
    flyIn
  ]
})

export class system_dictionaryComponent implements OnInit {
  public showBoolean = false;//用来控制子页面显示与否
  public addParentDirUrl: string = url.url+'/app2/web/manage/catagory/add';
  public addChildDirUrl: string = url.url+'/app2/web/manage/catagory/add';
  public deleteDirUrl: string = url.url+'/app2/web/manage/catagory/delete';
  public deleteChildDirUrl: string = url.url+'/app2/web/manage/catagory/delete';
  public getDirectorUrl: string = url.url+"/app2/web/manage/catagory/list";
<<<<<<< HEAD
  public imageUrl: string = url.url +'/';
=======
  public imageUrl: string = url.url+'/';
>>>>>>> 5f3ac8f2aa524649cf71e4329f79f1081d6b2514
  public updataChildDirUrl: string = url.url+'/app2/web/manage/catagory/update';
  public deleteImageUrl: string = 'http://rapapi.org/mockjsdata/20823/upload/images';
  public theads: Array<any> = ["子类名字", "说明文字", "icon", "操作"];
  public getDirectorParams: object = {page: 0, size: 10, sort: 'id'};
  public deleteChildParams: any ={};
  //用来控制图片上传，删除图片处，所以图片数据都需要推到这个数组里
  public firstUnloadImageArray: any = [];
  public categorys: any = [];
  //用来保存上传的图片
  public publicArticleImage: Array<any> = [];
  //用来控制loading显示与否
  public showLoading: boolean = true;
  //用来初始化图片上传插件里的图片
  public unloadImageArray: any = [];
  //用来展示删除的模态框
  public showDeleteConfirm: boolean = false;
  //用来保存唯一的图标，展示在前端页面上
  public categoryUniqueDetail: any = {catagoryName: '', content: '', icon: ''};
  public newParentDir: string;
  //用来展示添加父类名；
  public showAddParent: boolean = false;
  public show: boolean = true;
  public uniqueHttpurl:any = {httpPost:false,httpPut:false};

  constructor(private fileInputPlugin: FileInputPluginService,
              private http: HttpService
  ) {
  }

  ngOnInit() {
    this.http.httpGet(this.getDirectorUrl, this.getDirectorParams)
      .subscribe((res) => {
        console.log(res);
        this.categorys = res.results.catagorites.content;
        this.show = false;
      });

  }

  // newsTitle(event){
  //   this.inputValue.articleTitle=event.target.value
  // }
  // newsDirectory(event){
  //   this.inputValue.newsDir=event.target.value;
  // }
  // newsAuthor(event){
  //   this.inputValue.newsAuthor=event.target.value;
  // }
  editSubCategory(value) {
    this.uniqueHttpurl.httpPut = true;
    this.showBoolean = true;
    let uniqueValue = value;
    let initalPreviewConfig: any = [];
    this.firstUnloadImageArray.push({address:uniqueValue.icon});
    let imgEle = `${this.imageUrl}${uniqueValue.icon}`;
    console.log(imgEle);
    // this.firstUnloadImageArray.push(uniqueValue.icon);
    this.unloadImageArray.push(imgEle);
    // this.loadImagePlugin();
    this.categoryUniqueDetail = value;
    let obj = {
      caption: uniqueValue.icon,
      width: "120px",
      url: this.deleteImageUrl,
      key: uniqueValue.icon
    };
    initalPreviewConfig.push(obj);
    this.loadImagePlugin(this.unloadImageArray,initalPreviewConfig);
    console.log(value)
  }

  addParentDir() {
    this.newParentDir = '';
    this.showAddParent = true;
  }
  onSubmit() {
    this.categoryUniqueDetail.icon = this.firstUnloadImageArray[0].address;
    console.log(this.categoryUniqueDetail);
    if(this.uniqueHttpurl.httpPost){
      this.http.httpPost(this.addChildDirUrl, this.categoryUniqueDetail)
        .subscribe((res) => {
          console.log("成功添加");
          this.showBoolean = false;
          this.ngOnInit();
        });
    }else if(this.uniqueHttpurl.httpPut){
      this.http.httpPut(this.updataChildDirUrl,this.categoryUniqueDetail)
        .subscribe((res)=>{
        console.log(res);
        console.log("更新成功");
        this.showBoolean = false;
        this.ngOnInit()
        });
      console.log("调用更新接口")
    }





    this.uniqueHttpurl = {httpPost:false,httpPut:false}
  }
  addChildDirector(index) {
    this.uniqueHttpurl.httpPost = true;
    this.firstUnloadImageArray = [];
    let initalPreviewConfig:any = [];
    this.categoryUniqueDetail = {catagoryName: '', content: '', icon: '', parentId: index};
    this.showBoolean = true;
    this.loadImagePlugin(this.firstUnloadImageArray,initalPreviewConfig);

  }
  loadImagePlugin(preView,initalPreviewConfig) {
    this.fileInputPlugin.showFileInputPlugin("#input-gly-9", 1, preView, initalPreviewConfig);
    this.fileInputPluginPredelete("#input-gly-9");
    this.fileInputPluginDelete("#input-gly-9");
    this.fileInputPluginUploaded("#input-gly-9", 'catagoryChild');
  }

  deleteParentDir(index) {
    if (window.confirm("确定删除吗?")) {
      this.http.httpDelete(this.deleteDirUrl, {id: index})
        .subscribe((res) => {
          console.log(res);
          this.ngOnInit()
        })
    }
  }

  deleteProduceSure() {
    this.http.httpDelete(this.deleteChildDirUrl, this.deleteChildParams)
      .subscribe((res) => {
      this.showDeleteConfirm = false;
        this.ngOnInit()
      })
  }

  concelAddDir() {
    this.showAddParent = false;
  }

  childCateoryNameHandle(e) {
    this.categoryUniqueDetail.catagoryName = e.target.value;
  }

  saveParentDir() {
    this.http.httpPost(this.addParentDirUrl, {content: '', icon: '', catagoryName: this.newParentDir, parentId: null})
      .subscribe((res) => {
        console.log(res);
        console.log('添加成功')
      });
    this.showAddParent = false;
    console.log(this.newParentDir)
  }

  childCateoryIntroHandle(e) {
    this.categoryUniqueDetail.content = e.target.value;
  }





  fileInputPluginPredelete(ele) {
    $(ele).on("filepredelete", function (event, key, jqXHR, data) {
      console.log(this.firstUnloadImageArray);
      console.log(key);
      for (let i = 0, len = this.firstUnloadImageArray.length; i < len; i++) {
        let pName = this.firstUnloadImageArray[i].address;
        console.log(pName);
        if (pName === key) {
          // console.log(i);
          // j = i;
          this.firstUnloadImageArray.splice(i, 1);
          return;
        }
      }
      // this.firstUnloadImageArray.splice(j,1);
    }.bind(this))
  }

  fileInputPluginDelete(ele) {
    $(ele).on('filesuccessremove', function (event, data, id, index) {
      console.log(data);
      console.log(id);
      console.log(index);
      let deleteName = $('#' + data + ' img').attr('title');
      console.log(deleteName);
      let newArray = [];
      // this.firstUnloadImageArray = this.firstUnloadImageArray.filter((item)=>item.imgName === deleteName);
      for (let i = 0, len = this.firstUnloadImageArray.length; i < len; i++) {
        if (this.firstUnloadImageArray[i].imgName === deleteName) {
          this.firstUnloadImageArray.splice(i, 1);
        }
      }
      console.log(this.firstUnloadImageArray);
      // event.preventDefault();
      // console.log(index)
    }.bind(this))
  }


  fileInputPluginUploaded(ele, position) {
    $(ele).on("fileuploaded", function (a, data, c, d) {
      console.log("成功上传图片,获取数据");
      // console.log(data);
      // console.log(a);
      // console.log(c);
      // console.log(d);
      let obj: any = {};
      let image1Response = data.response;
      console.log(data);
      let pName: string = '';
      let files = data.files;
      console.log(files);
      for (let i = 0, len = files.length; i < len; i++) {
        if (files[i] !== 'undefined') {
          console.log(files[i]);
          pName = files[i].name;
          break;
        }
      }
      obj.address = image1Response.results.path;
      obj.imgName = pName;
      obj.position = position;
      this.firstUnloadImageArray.push(obj);
      // this.unloadImageArray.push(obj);
      console.log(this.firstUnloadImageArray);
      // this.image1DataFromModal.emit(image1Response)
    }.bind(this));
  }

  closeAddChildModal() {
    this.showBoolean = false;
  }

  closeConfirm() {
    this.showDeleteConfirm = false;
  }

  deleteSubCategory(value) {
    console.log(value);
    this.deleteChildParams.id = value.id;
    this.showDeleteConfirm = true;
    this.ngOnInit();

  }


}
